package com.mspbots.rule.exceptions.triggerEscalation;

import cn.hutool.json.JSONUtil;
import com.mspbots.api.config.ApiProperties;
import com.mspbots.api.service.TenantRuleService;
import com.mspbots.api.service.TenantUserService;
import com.mspbots.rule.exceptions.BaseRule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

/**
 * @author Dinnes
 */
@Slf4j
@Component
public abstract class TriggerEscalationBaseRule extends BaseRule {

    protected TenantUserService tenantUserService;

    protected TenantRuleService tenantRuleService;

    protected boolean checkEscalationUser(TriggerEscalationDTO entry) {
        MessagesDTO messages = new MessagesDTO();
        messages.setUserId(entry.getUserId());
//        messages.setBusinessId(900 + entry.getRuleId() + entry.getUserId());
        messages.setEscalation(true);
        messages.setRuleId(entry.getRuleId());
        messages.setTenantId(entry.getTenantId());
        messages.setBusinessType("escalationUser");
        return messagesService.checkEscalation(messages);
    }

    protected boolean checkEscalationManager(TriggerEscalationDTO entry, Map<String, Object> manager) {
        MessagesDTO messages = new MessagesDTO();
        messages.setUserId(Long.valueOf(String.valueOf(manager.get("manager"))));
//        messages.setBusinessId(900 + entry.getRuleId() + entry.getUserId());
        messages.setEscalation(true);
        messages.setRuleId(entry.getRuleId());
        messages.setTenantId(entry.getTenantId());
        messages.setBusinessType("escalationManager");
        return messagesService.checkEscalation(messages);
    }

    protected StringBuilder escalationLink(Long tenantUserId, Long ruleId, TenantUsersMappingDTO tenantUserMappingDTO) {
        LocalDateTime nowtime = LocalDateTime.now();

        StringBuilder redirectParams = new StringBuilder()
                .append("sentTimeFrom=").append(LocalDate.now().minusDays(LocalDate.now().getDayOfWeek().getValue() - 1) + "T00:00:00")
                .append("&tenantUserId=").append(tenantUserId)
                .append("&ruleId=").append(ruleId);
        StringBuilder params = new StringBuilder()
                .append("teamsUserId=").append(tenantUserMappingDTO.getTeamsUserId())
                .append("&redirectUrl=/report/MessageReport")
                .append("&redirectParams=").append(Base64Utils.encodeToString(redirectParams.toString().getBytes(StandardCharsets.UTF_8)));
        return new StringBuilder().append("<br>")
                .append("<span style='color:#999d9c;font-size:10px;'>")
                .append("--[<a href='" + apiProperties.getPortalUrl() + "/sso")
                .append("?params=").append(Base64Utils.encodeToString(params.toString().getBytes(StandardCharsets.UTF_8))).append("'>")
                .append("Click here to view detail")
                .append("</a>]")
                .append("</span>--")
                .append("<span style='color:#999d9c;font-size:10px;'>[")
                .append(tenantUserMappingDTO.getUserName())
                .append("]&nbsp;")
                .append("[")
                .append(nowtime.plusHours(Integer.parseInt(tenantUserMappingDTO.getTz().substring(0, 3))).format(DateTimeFormatter.ofPattern("MM/dd/yy HH:mm")))
                .append("/")
                .append(tenantUserMappingDTO.getTzStr())
                .append("]")
                .append("</span>");
    }

    protected StringBuilder escalationDetial(Long tenantUserId, Long ruleId, TenantUserService tenantUserService, TenantUsersMappingDTO tenantUserMappingDTO) {
        TenantUserDTO tenantUserDTO = tenantUserService.findById(tenantUserId);
        int offset = 0;
        Map<String, Object> params = Map.of("tenantId", tenantUserDTO.getTenantId(), "tenantUserId", tenantUserId);
        TenantUserConfigurationDTO tenantUserConfigurationDTO = this.coreClient.get("/tenant/user-configuration/keyword/work_time", params, TenantUserConfigurationDTO.class).block();
        if (!StringUtils.isEmpty(tenantUserConfigurationDTO)) {
            offset = Integer.parseInt(JSONUtil.parseObj(tenantUserConfigurationDTO.getKeywordValue()).get("offset").toString().substring(0, 3));
        }
        Date createDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String imptimeBegin = null;
        Calendar cal = Calendar.getInstance();
        cal.setTime(createDate);
        if (cal.get(Calendar.DAY_OF_WEEK) == 1) {
            cal.add(Calendar.DATE, -6);
            cal.add(Calendar.HOUR, offset);
            imptimeBegin = sdf.format(cal.getTime());
        } else if (cal.get(Calendar.DAY_OF_WEEK) == 2) {
            cal.add(Calendar.HOUR, offset);
            imptimeBegin = sdf.format(cal.getTime());
        } else {
            cal.add(Calendar.DATE, 2 - cal.get(Calendar.DAY_OF_WEEK));
            cal.add(Calendar.HOUR, offset);
            imptimeBegin = sdf.format(cal.getTime());
        }
        LocalDateTime nowtime = LocalDateTime.now();
        return new StringBuilder().append("<br>")
                .append("<span style='color:#999d9c;font-size:10px;'>")
                .append("--[<a href='" + apiProperties.getPortalUrl() + "/102322" + "/report/MessageReport?" + "tenantUserName="
                        + tenantUserDTO.getFirstname() + " " + tenantUserDTO.getLastname()
                        + "&ruleId=" + ruleId + "&escalation=" + true + "&tenantId=" + tenantUserDTO.getTenantId() + "&createDateFrom=" + imptimeBegin).append("'>")
                .append("Click here to view detail")
                .append("</a>]")
                .append("--")
                .append("<span style='color:#999d9c;font-size:10px;'>[")
                .append(tenantUserMappingDTO.getUserName())
                .append("]&nbsp;")
                .append("[")
                .append(nowtime.plusHours(Integer.parseInt(tenantUserMappingDTO.getTz().substring(0, 3))).format(DateTimeFormatter.ofPattern("MM/dd/yy HH:mm")))
                .append("/")
                .append(tenantUserMappingDTO.getTzStr())
                .append("]")
                .append("</span>");
    }

    public void setTenantUserService(TenantUserService tenantUserService) {
        this.tenantUserService = tenantUserService;
    }

    public void setTenantRuleService(TenantRuleService tenantRuleService) {
        this.tenantRuleService = tenantRuleService;
    }

    public void setApiProperties(ApiProperties apiProperties) {
        this.apiProperties = apiProperties;
    }

}
